//
//  HZJTreeCell.swift
//  HZJTreeView
//
//  Created by 何治军 on 2020/6/18.
//  Copyright © 2020 何治军. All rights reserved.
//

import UIKit
import SnapKit

var BoundaryMargin:CGFloat{
    return 30
}

class HZJTreeCell: UITableViewCell {
    
    var model:HZJTreeViewModelProtocol? = nil {
        didSet{
            if let new = model {
                self.btnIcon.isHidden = new.childModels.count == 0
                self.btnIcon.isSelected = new.isOpen
                self.labTitle.textColor = new.isOpen ? .green : .red
                self.labTitle.text = (new as? HZJTreeModel)?.titleInfo
                if let a = new as? HZJTreeModel {
                    self.labTitle.text = a.titleInfo + (a.isOpen ? "打开" : "关闭")
                }
                else if let b = new as? HZJTreeModel2 {
                    self.labTitle.text = b.myTitle + (b.isOpen ? "打开" : "关闭")
                }
                self.updateTheConstraints()
            }else{
                self.btnIcon.isSelected = false
                self.labTitle.text = nil
            }
        }
    }
    
    /// 根据modelType修改约束
    private func updateTheConstraints() {
        self.btnIcon.snp.updateConstraints { (make) in
            make.left.equalToSuperview().offset(BoundaryMargin * CGFloat((self.model != nil) ? self.model!.type : 1)).priority(.high)
        }
    }
        
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        self.backgroundColor = .white
        self.addSubview(btnIcon)
        self.addSubview(labTitle)
        btnIcon.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(BoundaryMargin).priority(.high)
            make.top.equalToSuperview().offset(10)
            make.width.height.equalTo(20)
        }
        labTitle.snp.makeConstraints { (make) in
            make.left.equalTo(btnIcon.snp.right).offset(6)
            make.top.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-BoundaryMargin)
            make.centerY.equalToSuperview()
            make.height.greaterThanOrEqualTo(20)
            make.width.greaterThanOrEqualToSuperview().multipliedBy(0.25)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var btnIcon: UIButton = {
        let v = UIButton()
        v.setImage(UIImage(named: "arrow_down")?.withRenderingMode(.alwaysTemplate), for: .normal)
        v.setImage(UIImage(named: "arrow_top")?.withRenderingMode(.alwaysTemplate), for: .selected)
        v.isUserInteractionEnabled = false
        return v
    }()
    
    lazy var labTitle: UILabel = {
        let v = UILabel()
        v.font = UIFont.systemFont(ofSize:13)
        v.numberOfLines = 0
        v.textColor = .green
        return v
    }()
}
